import _ from 'lodash'
import {RequestCode, SUCCESS} from "./RequestCode.js";
import {myRequest} from "../utils/MyRequest.js"
import {localSetUserLogin, useUserStore} from "../store/index.js";

const store = useUserStore()
export async function userLogin(userAccount, userPassword) {
    //检查参数是否为空
    if (_.isEmpty(userAccount) || _.isEmpty(userPassword)) {
        return {
            code: RequestCode.PARAMS_ERROR.code,
            message: '用户名或密码不能为空'
        }
    }
    const res =  await myRequest.post('/user/login', {
        userAccount, userPassword
    });
    if (res.code === SUCCESS.code){
        localSetUserLogin(true)
    }else{
        localSetUserLogin(false)
    }
    return res;

}

/**
 * 注册
 *     private String userAccount;
 *     private String userPassword;
 *     private String checkPassword;
 */

export async function userRegister(userAccount, userPassword, checkPassword) {
    //检查参数是否为空
    if (_.isEmpty(userAccount) || _.isEmpty(userPassword) || _.isEmpty(checkPassword)) {
        return {
            code: RequestCode.PARAMS_ERROR.code,
            message: '用户名或密码不能为空'
        }
    }
    if (userPassword !== checkPassword) {
        return {
            code: RequestCode.PARAMS_ERROR.code,
            message: '两次输入的密码不一致'
        }
    }
    return await myRequest.post('/user/register', {
        userAccount, userPassword, checkPassword
    });

}
export async function getCurrentUser(path) {
    const res =  await myRequest.get('/user/current');
    if (res.code === SUCCESS.code){
        store.userinfo = res.data;
        store.userId = res.data.id;
        store.isLogin = true;
        store.userIsLogin = true
        localSetUserLogin(true)
    }else{
        store.userIsLogin = false
        store.isLogin = false
        localSetUserLogin(false)
        // Message.info('登录过期，请重新登录')
        // if (path){
        //     await router.push('/login?redirect=' + path)
        // }else{
        //     await router.push('/login')
        // }
    }
}

/**
 * 分页获取用户
 */
export async function getUserListApi(page, size,userName) {
    return await myRequest.get('/user/page', {
        params: {
            page, size,userName
        }
    });
}


/**
 * 修改用户
 */
export async function updateUserApi(data) {
    return await myRequest.post('/user/update', data);
}

/**
 * 新增用户
 */
export async function addUserApi(data) {
    return await myRequest.post('/user/add', data);
}

/**
 * 退出登录
 * /logout
 */
export async function logoutApi() {
    return await myRequest.get('/user/logout');
}

/**
 * 删除用户
 */
export async function deleteUserApi(id) {
    return await myRequest.get('/user/delete/' + id);
}
